<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElTag, ElMessageBox, ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { Table } from '@/components/Table'
import { ucUserEditAdminApi, ucUserEditPasswordAdminApi } from '@/api/uc/user'
import {
  ucOrgUserListApi,
  ucOrgUserAddApi,
  ucOrgUserDelAdminApi
  //ucOrgUserBatchDelApi,
} from '@/api/uc/orgUser'
import { useTable } from '@/hooks/web/useTableTest'
// import { TableData } from '@/api/uc/user/types'
import { h, ref, unref, reactive } from 'vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import Add from './components/Add.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'

// const iconRole = useIcon({ icon: 'eos-icons:role-binding-outlined' })
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })
const iconPassword = useIcon({ icon: 'carbon:password' })

const route = useRoute()
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: ucOrgUserListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

// 设置固定值
tableObject.fixedSearch = { org_id: route.query.org_id }
getList()

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'org_user_id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'username',
    label: '用户名',
    width: 100,
    search: {
      show: true
    }
  },
  {
    field: 'is_owner',
    label: '是否所有者',
    width: 100,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return h(
        ElTag,
        {
          type: cellValue == '1' ? 'success' : cellValue == '0' ? 'warning' : 'danger'
        },
        () => (cellValue == '1' ? '是' : cellValue == '0' ? '否' : '未知')
      )
    },
    form: {
      show: false
    }
  },

  {
    field: 'nickname',
    label: '姓名',
    fixed: 'left',
    width: 100,
    search: {
      show: true
    }
  },
  {
    field: 'email',
    label: '电子邮箱',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'mobile',
    label: '手机号',
    width: 150,
    search: {
      show: true
    }
  },
  // {
  //   field: 'is_stop',
  //   label: '是否停用',
  //   width: 80,
  //   formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
  //     return h(
  //       ElTag,
  //       {
  //         type: cellValue == '0' ? 'success' : cellValue == '1' ? 'warning' : 'danger'
  //       },
  //       () => (cellValue == '0' ? '启用' : cellValue == '1' ? '停用' : '未知')
  //     )
  //   },
  //   form: {
  //     component: 'Select',
  //     componentProps: {
  //       options: [
  //         {
  //           label: '启用',
  //           value: '0'
  //         },
  //         {
  //           label: '停用',
  //           value: '1'
  //         }
  //       ]
  //     }
  //   }
  // },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    form: {
      show: false,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'update_time',
    label: '修改时间',
    width: 170,
    form: {
      show: false,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'action',
    width: 240,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

// const delLoading = ref(false)

// const delData = async () => {
//   const { getSelections } = methods
//   const selections = await getSelections()
//   const ids = selections.map((v) => v.org_user_id)
//   delLoading.value = true
//   ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
//     confirmButtonText: t('common.delOk'),
//     cancelButtonText: t('common.delCancel'),
//     type: 'warning'
//   })
//     .then(async () => {
//       let res = await ucOrgUserBatchDelApi({ ids: ids.join(',') })
//         .catch(() => {})
//         .finally(() => {
//           delLoading.value = false
//         })
//       if (res) {
//         getList()
//       }
//     })
//     .catch(() => {})
// }

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'password':
      ElMessageBox.prompt('请填写需要修改的密码', '修改密码', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputType: 'password'
        // inputErrorMessage: 'Invalid Email'
      })
        // ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        //   confirmButtonText: '确认',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // })
        .then(async ({ value }) => {
          let res: any = await ucUserEditPasswordAdminApi({
            user_id: row.user_id,
            password: value
          }).catch(() => {})
          if (res) {
            ElMessage({
              type: 'success',
              message: res.msg
            })
          }
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        org_id: route.query.org_id,
        is_stop: '0',
        state: '2'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.org_user_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

// 单个删除
const apiDel = async (org_user_id) => {
  let delRes = await ucOrgUserDelAdminApi({ org_user_id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
const addRef = ref<ComponentRef<typeof Add>>()

const loading = ref(false)

const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any
          let res: any = await ucUserEditAdminApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            ElMessage({
              type: 'success',
              message: res.msg
            })
            getList()
          }
        }
      })

      break
    case 'add':
      const add = unref(addRef)
      await add?.elFormRef()?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await add?.getData()) as any
          let res: any = await ucOrgUserAddApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <!-- <div class="mb-10px"> -->
    <!-- <ElButton type="primary" @click="action('add')">新增</ElButton> -->
    <!-- <ElButton :loading="delLoading" type="danger" @click="delData()"> 批量删除 </ElButton> -->
    <!-- </div> -->

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconEdit" @click="action('edit', row)" title="编辑" />
        <ElButton circle :icon="iconPassword" @click="action('password', row)" title="修改密码" />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看详情" />
        <ElButton circle :icon="iconDel" @click="action('del', row)" title="删除" />
        <!-- <ElButton
          v-if="row.is_owner == 1"
          circle
          :icon="iconRole"
          @click="action('setSysRole', row)"
          title="设置系统角色"
        /> -->
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Add v-if="actionType == 'add'" ref="addRef" :data="tableObject.currentRow" />
    <Edit
      v-if="actionType == 'edit'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'see'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
